package com.zhouheng.springbootmultithreading.tuling.threadbase;

import lombok.SneakyThrows;

/**
 * 线程间通信
 * volatile演示
 * 最终效果两个线程交替执行
 * 但是这样操作while(true)CPU消耗会很大，建议用scheduled+线程池周期执行，或while里加Thread.sleep
 * 本例使用Thread.sleep适当的进行了优化
 */
public class VolatileDemo {

    private static volatile boolean flag = true;

    public static void main(String[] args) {

        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                while (true) {
                    if (flag) {
                        System.out.println("trun on");
                        flag = false;
                    }
                    Thread.sleep(1000 * 5);
                }
            }
        }).start();

        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                while (true) {
                    if (!flag) {
                        System.out.println("trun off");
                        flag = true;
                    }
                    Thread.sleep(1000 * 5);
                }
            }
        }).start();
    }
}